package com.xlh.util;

import com.alibaba.fastjson.JSONObject;
import com.xlh.constant.UserConstant;
import com.xlh.dto.system.IpRegionDTO;
import com.xlh.dto.system.IpRegionDataDTO;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.helpers.MessageFormatter;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpServletRequest;

/**
 * request工具类
 *
 * @author cheer
 */
public class RequestUtil {

    private static RestTemplate restTemplate = SpringContextUtil.getBean(RestTemplate.class);

    /**
     * 获取请求Ip地址
     */
    public static String getIpAddress(HttpServletRequest request) {
        String xForwardedFor = request.getHeader("X-Forwarded-For");
        if (StringUtils.isNotBlank(xForwardedFor) && !"unKnown".equalsIgnoreCase(xForwardedFor)) {
            //多次反向代理后会有多个ip值，第一个ip才是真实ip
            int index = xForwardedFor.indexOf(',');
            if (index != -1) {
                return xForwardedFor.substring(0, index);
            } else {
                return xForwardedFor;
            }
        }

        String xRealIp = request.getHeader("X-Real-IP");
        if (StringUtils.isNotBlank(xRealIp) && !"unKnown".equalsIgnoreCase(xRealIp)) {
            return xRealIp;
        }

        if (StringUtils.isBlank(xRealIp) || "unknown".equalsIgnoreCase(xRealIp)) {
            xRealIp = request.getHeader("Proxy-Client-IP");
        }
        if (StringUtils.isBlank(xRealIp) || "unknown".equalsIgnoreCase(xRealIp)) {
            xRealIp = request.getHeader("WL-Proxy-Client-IP");
        }
        if (StringUtils.isBlank(xRealIp) || "unknown".equalsIgnoreCase(xRealIp)) {
            xRealIp = request.getHeader("HTTP_CLIENT_IP");
        }
        if (StringUtils.isBlank(xRealIp) || "unknown".equalsIgnoreCase(xRealIp)) {
            xRealIp = request.getHeader("HTTP_X_FORWARDED_FOR");
        }
        if (StringUtils.isBlank(xRealIp) || "unknown".equalsIgnoreCase(xRealIp)) {
            xRealIp = request.getRemoteAddr();
        }
        return xRealIp;
    }

    public static IpRegionDataDTO getRegionInfo(String ip) {
        String url = MessageFormatter.arrayFormat(UserConstant.GET_REGION_URL, new String[]{ip}).getMessage();
        String responseInfo = interfaceUtil(url);
        if (StringUtils.isNotBlank(responseInfo)) {
            IpRegionDTO ipRegionVO = JSONObject.parseObject(responseInfo, IpRegionDTO.class);
            if (ipRegionVO != null) {
                return ipRegionVO.getData();
            }
        }
        return null;
    }

    /**
     * get请求
     *
     * @param path 地址
     * @return
     */
    private static String interfaceUtil(String path) {
        ResponseEntity<String> responseEntity = restTemplate.getForEntity(path, String.class);
        if (responseEntity.getStatusCodeValue() == 200) {
            return responseEntity.getBody();
        }
        return null;
    }

}
